﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Util;
using Newtonsoft;
using LeSoft.Application.Entity;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_PStructPublishController : MvcControllerBase
    {
        //
        // GET: /ResourceManage/RS_PStructPublish/

        private PStructPublishBLL PsPBbll = new PStructPublishBLL();
        private RoomBLL rbll = new RoomBLL();
        private PStructBLL pstructBLL = new PStructBLL();
        private OrganizeBLL obll = new OrganizeBLL();
        private PStructCache pstructCache = new PStructCache();
        private RoomCache roomcahce = new RoomCache();
        private OrganizeCache organizeCache = new OrganizeCache();

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "房源发布首页", "Index")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "发布单", "Form")]
        public ActionResult Form()
        {
            //是否存在自动编号
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(Convert.ToInt32(CodeRuleEnum.PStructPubishCode).ToString());
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "添加房源", "AddForm")]
        public ActionResult AddForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "发布单审核", "AiditForm")]
        public ActionResult AiditForm()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 发布撤回房产树
        /// </summary>
        /// <param name="State">1-发布（准备房） 2-撤回（待租）</param>
        /// <param name="OrganizeId">组织机构</param>
        /// <param name="lst">界面已选id</param>
        /// <returns></returns> 
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "房产树待复选框", "GetTree")]
        public ActionResult GetTree(string State, string OrganizeId, string lst)
        {

            OrganizeId = organizeCache.GetSonOrganizeId(OrganizeId);
            var PRlst = PsPBbll.GetPStructTreeList(State.ToInt(), OrganizeId);
            //var Plst = pstructBLL.GetList().OrderBy(t => t.Code).ToList();
            //Plst = Plst.Where(e => OrganizeId.Contains(e.OrganizeId) && e.Type < 5).ToList();
            var treeList = new List<TreeEntity>();
            //foreach (PStructEntity item in Plst)
            //{
            //    #region 树结构
            //    TreeEntity tree = new TreeEntity();
            //    bool hasChildren = true;
            //    tree.id = item.Id;
            //    tree.text = item.Name;
            //    tree.value = item.Type.ToString();
            //    tree.title = item.AllCode;
            //    tree.Attribute = "PSAllName";
            //    tree.AttributeValue = item.AllName;
            //    tree.parentId = string.IsNullOrEmpty(item.ParentId) ? "0" : item.ParentId;
            //    tree.AttributeA = "Type";
            //    tree.AttributeValueA = item.Type.ToString();
            //    tree.showcheck = true;
            //    tree.isexpand = lst.Contains(item.Id);
            //    tree.checkstate = lst.Contains(item.Id) ? 1 : 0;
            //    tree.complete = true;
            //    tree.hasChildren = hasChildren;
            //    switch (item.Type)
            //    {
            //        case 1: tree.img = "fa fa-university"; break;
            //        case 2: tree.img = "fa fa-building-o"; break;
            //        case 4: tree.img = "fa fa-server"; break;
            //        case 5: tree.img = "fa fa-cube"; break;
            //        default:
            //            tree.img = "fa fa-th-list";
            //            break;
            //    }
            //    if (item.ActiveMark == 1)
            //        tree.imgstyle = "color:#2df12d";
            //    treeList.Add(tree);
            //    #endregion
            //}
            foreach (PStructEntity item in PRlst)
            {
                #region 树结构
                TreeEntity tree = new TreeEntity();
                bool hasChildren = PRlst.Count(t => t.ParentId == item.Id) > 0 ? true : false; ;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Type.ToString();
                tree.title = item.AllCode;
                tree.Attribute = "PSAllName";
                tree.AttributeValue = item.AllName;
                tree.parentId = string.IsNullOrEmpty(item.ParentId) ? "0" : item.ParentId;
                tree.AttributeA = "Type";
                tree.AttributeValueA = item.Type.ToString();
                tree.showcheck = true;
                tree.isexpand = lst.Contains(item.Id);
                tree.checkstate = lst.Contains(item.Id) ? 1 : 0;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                switch (item.Type)
                {
                    case 1: tree.img = "fa fa-university"; break;
                    case 2: tree.img = "fa fa-building-o"; break;
                    case 4: tree.img = "fa fa-server"; break;
                    case 5: tree.img = "fa fa-cube"; break;
                    default:
                        tree.img = "fa fa-th-list";
                        break;
                }
                if (item.ActiveMark == 1)
                    tree.imgstyle = "color:#2df12d";
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeToJson());
        }


        /// <summary>
        /// 获取房屋实体集合
        /// </summary>
        /// <param name="queryJson">房间Id集合</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "获取房屋实体集合", "GetRoomEntity")]
        public ActionResult GetRoomEntity(string queryJson)
        {
            //var query = rbll.GetList().ToList();
            //var data = pstructBLL.GetList().ToList();
            //List<PStructEntity> lst = new List<PStructEntity>();
            //lst = data.Where(e => queryJson.Contains(e.Id) && e.Type == 5).ToList();
            //List<object> datalist = new List<object>();
            //foreach (var item in lst)
            //{
            //    var s = query.FirstOrDefault(e => e.PStructId == item.Id);
            //    var ety = new
            //    {
                    //Id = item.Id,
                    //Pavilionion = item.AllName,
                    //RoomCode = item.Code,
                    //PStructId = item.Id,
                    //RoomName = item.Name,
                    //RoomType = s.IsEmpty() ? "0" : s.HouseTypeName,
                    //RoomState = s.IsEmpty() ? null : s.State,
                    //Area = s.IsEmpty() ? null : s.Area,
                    //MonthlyRent = s.IsEmpty() ? null : s.MonthlyRent,
                    //EMoveInDate = s.IsEmpty() ? null : s.EMoveInDate,
                    //RoomDetail = pstructBLL.GetRoomEntity(item.Id).RoomDetailList,
                    //IsPublishToPC= s.IsEmpty() ? null : s.IsPublishToPC,
                    //IsPublish = s.IsEmpty() ? null : s.IsPublish,
                    //IsPublishToOther = s.IsEmpty() ? null : s.IsPublishToOther,
                    //IsPublishOther = s.IsEmpty() ? null : s.IsPublishOther,
            //    };
            //    if (data.Count(e => e.ParentId == item.Id) == 0)
            //    {
            //        datalist.Add(ety);
            //    }

            //};
           queryJson= queryJson.TrimEnd(',');
            var datalist=PsPBbll.GetRoomList(queryJson);
            return Content(datalist.ToJson());


        }
        /// <summary>
        /// 获取房间物品集合
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="IsSubmit"></param>
        /// <param name="BillId"></param>
        /// <returns></returns>
        public ActionResult GetRoomDetial(string keyValue, int IsSubmit, string BillId)
        {
            if (IsSubmit <2)
            {
                var data = pstructBLL.GetRoomEntity(keyValue).RoomDetailList;
                return Content(data.ToJson());
            }
            else
            {
                var query = PsPBbll.GetPStructPublishBillDetailEntityList(BillId);
                var data = query.Where(e => e.PStructId == keyValue).FirstOrDefault();
                return Content(data.ProductListDeatil);
            }

        }

        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "数据列表", "GetPagList")]
        public ActionResult GetPagList(Pagination pagination, string queryJson)
        {

            var str = queryJson.ToJObject();

            if (!str["OrganizeId"].IsEmpty())
            {
                string OrganizeId = organizeCache.GetSonOrganizeId(str["OrganizeId"].ToString());
                str["OrganizeId"] = OrganizeId;
            }
            var Json = str.ToString();
            var data = PsPBbll.GetPagList(pagination, Json);
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 获取房源信息实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "房源信息", "GetPStructPublishBillEntity")]
        public ActionResult GetPStructPublishBillEntity(string keyValue)
        {

            var data = PsPBbll.GetPStructPublishBillEntity(keyValue);
            var query = PsPBbll.GetPStructPublishBillDetailEntityList(keyValue).ToList();
            var query1 = rbll.GetList().ToList();
            List<object> datalist = new List<object>();
            foreach (var item in query)
            {
                var data1 = pstructBLL.GetEntity(item.PStructId);
                var s = query1.FirstOrDefault(e => e.PStructId == item.PStructId);
                var d = new
                {
                    Id = item.Id,
                    PStructId = item.PStructId,
                    Pavilionion = data1.IsEmpty() ? "" : data1.AllName,
                    RoomCode = data1.IsEmpty() ? "" : data1.Code,
                    RoomName = data1.IsEmpty() ? "" : data1.Name,
                    RoomType = s.IsEmpty() ? "0" : s.HouseTypeName,
                    RoomState = s.IsEmpty() ? null : s.State,
                    IsPublish = item.IsPublish,
                    IsPublishToPC = item.IsPublishToPC,
                    IsPublishToOther = item.IsPublishToOther,
                    IsPublishOther = item.IsPublishOther,
                    Area = s.IsEmpty() ? null : s.Area,
                    MonthlyRent = s.IsEmpty() ? null : (s.State == 0 ? s.MonthlyRent : (data.Category == "1" ? item.MonthlyRent : s.MonthlyRent)),
                    EMoveInDate = s.IsEmpty() ? null : s.EMoveInDate
                };

                if (query1.Count(e => e.ParentId == item.PStructId) == 0)
                {
                    datalist.Add(d);
                }

            }
            var Data = new
            {
                data1 = data,
                data2 = datalist
            };
            return Content(Data.ToJson());
        }

        /// <summary>
        /// 获取房源信息实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "单据明细", "GetPStructPublishBillDetailEntity")]
        public ActionResult GetPStructPublishBillDetailEntity(string keyValue)
        {
            var data = PsPBbll.GetPStructPublishBillEntity(keyValue);
            var query = PsPBbll.GetPStructPublishBillDetailEntityList(keyValue).ToList();
            var query1 = rbll.GetList().ToList();
            List<object> datalist = new List<object>();
            foreach (var item in query)
            {
                var data1 = pstructBLL.GetEntity(item.PStructId);
                var s = query1.FirstOrDefault(e => e.PStructId == item.PStructId);
                var d = new
                {
                    Id = item.Id,
                    PStructId = item.PStructId,
                    Pavilionion = data1.IsEmpty() ? "" : data1.AllName,
                    RoomCode = data1.IsEmpty() ? "" : data1.Code,
                    RoomName = data1.IsEmpty() ? "" : data1.Name,
                    RoomType = s.IsEmpty() ? "0" : s.HouseTypeName,
                    RoomState = s.IsEmpty() ? null : s.State,
                    IsPublish = s.IsEmpty() ? null : s.IsPublish,
                    Area = s.IsEmpty() ? null : s.Area,
                    MonthlyRent = s.IsEmpty() ? null : (s.State == 0 ? s.MonthlyRent : (data.Category == "1" ? item.MonthlyRent : s.MonthlyRent)),
                    EMoveInDate = s.IsEmpty() ? null : s.EMoveInDate
                };

                if (query1.Count(e => e.ParentId == item.PStructId) == 0)
                {
                    datalist.Add(d);
                }

            }
            return Content(datalist.ToJson());
        }
        #endregion

        #region 操作
        /// <summary>
        /// 保存房源信息
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="Type">类型</param>
        /// <param name="entity">房源实体</param>
        /// <param name="list">明细集合</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存房源信息", "SavePStructPublishBillEntity")]
        public ActionResult SavePStructPublishBillEntity(string keyValue, int type, string entity, string list)
        {           
            try
            {
                PStructPublishBillEntity obj = entity.ToObject<PStructPublishBillEntity>();
                List<PStructPublishBillDetailEntity> objlist = list.ToObject<List<PStructPublishBillDetailEntity>>();
                PsPBbll.SavePStructPublishBillEntity(keyValue, type, obj, objlist);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        /// <summary>
        /// 删除房源发布单
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Delete, "删除房源发布单", "RemovePStructPublishBillEntity")]
        public ActionResult RemovePStructPublishBillEntity(string keyValue)
        {
            var data = PsPBbll.GetPStructPublishBillEntity(keyValue);
            if (data.State == 1) //只有未提交的单子才可以删除 
            {
                try
                {
                    PsPBbll.RemovePStructPublishBillEntity(keyValue);
                    return Success("操作成");
                }
                catch (Exception)
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("订单已提交，无法删除");
            }

        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="Type"></param>
        /// <param name="entity"></param>
        /// <param name="lst"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "提交发布撤回单", "SubmitForm")]
        public ActionResult SubmitForm(string keyValue, int type, string entity, string list, string secSpan)
        {           
            try
            {
                PStructPublishBillEntity obj = entity.ToObject<PStructPublishBillEntity>();
                if (!secSpan.IsEmpty()) obj.SecSpan = Convert.ToDateTime(secSpan);
                List<PStructPublishBillDetailEntity> objlist = list.ToObject<List<PStructPublishBillDetailEntity>>();
                foreach (var a in objlist)
                {
                    RoomEntity room = rbll.GetEntity("PStructId", a.PStructId);
                    if(obj.Category == "1"&&!room.IsEmpty() ){
                        if (room.State == 0) continue;
                        else if (room.State == 1 && (room.IsPublishToPC != 1 || room.IsPublishToOther != 1)) continue;
                        else return Error(a.RoomName+"房间状态不满足业务，暂时无法提交！");
                    }
                    if (obj.Category == "2" && !room.IsEmpty())
                    {
                        if (room.State != 1) return Error(a.RoomName + "房间状态不满足业务，暂时无法撤回！");
                    }                    
                }               
                PsPBbll.SavePStructPublishBillEntity(keyValue, type, obj, objlist);
                return Success("提交成功");
            }
            catch (Exception e)
            {
                return Error("提交失败" + e.Message);
            }
        }
        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="Type">审批类型</param>
        /// <param name="Memo">审批说明</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "审批", "AiditBill")]
        public ActionResult AiditBill(string keyValue, string Type, int IsCheck, string Memo)
        {
            //var entity = PsPBbll.GetPStructPublishBillEntity(keyValue);
            //entity.CheckMemo = Memo;
            //entity.State = Convert.ToInt32(IsCheck) == 1 ? 4 : 3;
            //entity.CheckDate = DateTime.Now;
            //entity.CheckMan = OperatorProvider.Provider.Current().UserName;
            //entity.CheckManId = OperatorProvider.Provider.Current().UserId;
            //entity.IsCheck = Convert.ToInt32(IsCheck);
            //entity.EnabledMark = 1;
            //var Data = PsPBbll.GetPStructPublishBillDetailEntityList(entity.Id).ToList();
            //List<PStructPublishBillDetailEntity> list = new List<PStructPublishBillDetailEntity>();
            //foreach (var item in Data)
            //{
            //    PStructPublishBillDetailEntity lst = new PStructPublishBillDetailEntity();
            //    lst.PStructId = item.PStructId;
            //    list.Add(lst);
            //}
            try
            {
                PsPBbll.AuditForm(keyValue, IsCheck, Memo);
              //  PsPBbll.SavePStructPublishBillEntity(keyValue, Convert.ToInt32(Type), entity, list);
                return Success("审批成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        #endregion

    }
}
